<?php


namespace App\Services\Game;


use App\DTOS\Admin\EquipSendDTO;
use App\Models\Game\EquipSend;
use App\Models\Game\Server;
use Illuminate\Support\Facades\Http;
use App\Utils\MyLog;
use Illuminate\Support\Facades\Log;

// 主表 equip_send  , 子表  equip_send_items

class EquipSendService
{
    public function paginate(EquipSendDTO $DTO)
    {
        $pageSize = $DTO->getLimit();
        $page = $DTO->getPage();
        $model = EquipSend::query();


        return $model->orderByDesc('id')->paginate($pageSize,'*','page',$page);
    }

    public function sendById($id){
        $equipSend = EquipSend::query()->with('sendItems')->find($id);
        $QueryType = 0;
        $AttaItems = []; //附件物品列表
        foreach ($equipSend->sendItems as $sendItem) {
            $AddiAttr = [];
            $OreAddiAttr = [];
            $GemAttr = [];
            $SoulAttr = null; // {}
            $PetAttr = null; // {}
            $FsbId  = null;
            $FsbCurrExp  = null;
            if (!empty($sendItem->attribute)) {
                $AddiAttr = [];
                foreach($sendItem->attribute as $item) {
                    $AddiAttr[] = [
                        'Type'=>(int)$item['id'],
                        'Value'=>(int)$item['value'],
                    ];
                }
            }
            if (!empty($sendItem->ore)){
                $OreAddiAttr = [];
                foreach($sendItem->ore as $item) {
                    $OreAddiAttr[] = [
                        'Type'=>(int)$item['id'],
                        'Value'=>(int)$item['value'],
                    ];
                }
            }

            if (!empty($sendItem->gem)){
                $GemAttr = [];
                foreach($sendItem->gem as $item) {
                    $GemAttr[] = [
                        'GemId'=>(int)$item['id'],
                        'Type'=>(int)$item['Type'],
                        'Value'=>(int)$item['value'],
                    ];
                }
            }
            if (!empty($sendItem->soul_attr)){
                $soulObj = $sendItem->soul_attr;
                $AddiAttr = [];
                $soulAttrIds = data_get($soulObj,'soulAttrIds');
                $soulAttrValues = data_get($soulObj,'soulAttrValues');
                if (!empty($soulAttrIds)){
                    foreach ($soulAttrIds as $index=>$soulAttrId){
                        $AddiAttr[] = [
                            'Type'=>(int)$soulAttrId,
                            'Value'=>(int)$soulAttrValues[$index],
                        ];
                    }
                }
                foreach($soulObj as $key=>$value){
                    if ($value) {
                        $soulObj[$key] = (int)$value; //转整型
                    } else {
                        $soulObj[$key] = 0;
                    }
                }
                $SoulAttr = [
                    'Quality'=>data_get($soulObj,'quality'),
                    'Level'=>data_get($soulObj,'level'),
                    'Exp'=>data_get($soulObj,'exp'),
                    'Life'=>data_get($soulObj,'life'),
                    'Nimbus'=>data_get($soulObj,'nimbus'),
                    'PhyScore'=>data_get($soulObj,'phyScore'),
                    'MagScore'=>data_get($soulObj,'magScore'),
                    'feedPhyScore'=>data_get($soulObj,'feedPhyScore'),
                    'TalentId'=>data_get($soulObj,'soulTalentId'),
                    'SkillId'=>data_get($soulObj,'soulSkillId'),
                    'AddiAttr'=>!empty($AddiAttr)?$AddiAttr:null,
                    'LinHe'=>null,
                ];
            }

            if (!empty($sendItem->pet_attr)){
                $petObj = $sendItem->pet_attr;
                $AddiAttr = [];
                $Skill = [];

                $petSkillIds = data_get($petObj,'petSkillIds');
                $petAttrIds = data_get($petObj,'petAttrIds');
                $petAttrValues = data_get($petObj,'petAttrValues');

                if (!empty($petSkillIds)){
                    foreach($petSkillIds as $index=>$petSkillId){
                        $Skill[] = [
                            'CfgId'=>(int)$petSkillId,
                        ];
                    }
                }
                if (!empty($petAttrIds)){
                    foreach($petAttrIds as $index=>$petAttrId){
                        $AddiAttr[] = [
                                'CfgId'=>(int)$petAttrId,
                                'Value'=>(int)$petAttrValues[$index],
                        ];
                    }
                }

                $PetAttr = [
                    'Level'=>(int)data_get($petObj,'Level'),
                    'WuXing'=>(int)data_get($petObj,'WuXing'),
                    'Exp'=>(int)data_get($petObj,'Exp'),
                    'Fidelity'=>(int)data_get($petObj,'Fidelity'),
                    'BagNum'=>(int)data_get($petObj,'BagNum'),
                    'Name'=>data_get($petObj,'Name'),
                    'AddiAttr'=>!empty($AddiAttr) ? $AddiAttr: null,
                    'Skill'=>!empty($Skill) ? $Skill: null,
                ];
            }
            MyLog::info('查看传入仙魂珠的参数'.$sendItem->fsbAttr);
            if(!empty($sendItem->fsbAttr)){
                $fsbAttrJson = $sendItem->fsbAttr;
                $fsbObj = json_decode($fsbAttrJson, true);
                $FsbId = (int)data_get($fsbObj,'FsbId');
                $FsbCurrExp = (int)data_get($fsbObj,'FsbCurrExp');
            }
            $AttaItems[] = [
                'Id'=>$sendItem->equip_id,
                'Amount'=>$sendItem->send_num,
                "IntensifyLv"=>$sendItem->equip_level,
                "GemHoleCount"=>$sendItem->hole_num,
                "IsBinding"=> $sendItem->equip_bind,
                "AddiAttr"=>!empty($AddiAttr) ? $AddiAttr : null, //物品的属性
                "OreAddiAttr"=>!empty($OreAddiAttr) ? $OreAddiAttr : null, //物品的矿石
                "GemAttr"=>!empty($GemAttr) ? $GemAttr : null, //宝石
                "SoulAttr"=> $SoulAttr, //	魂魄魂晶属性
                "PetAttr"=> $PetAttr, //	魂魄魂晶属性
                "FsbId"=>$FsbId,
                "FsbCurrExp"=>$FsbCurrExp,

            ];
        }
        $RoleIdList = [];

        foreach ($equipSend->role_ids as $role_id) {
            $RoleIdList[] = [
                'Id'=>$role_id
            ];
        }

        $requestBody = [
            'QueryType'=> $QueryType ,//0.按收件人列表发送 1.本区所有角色
            'MailPid'=>(int)$id,
            'MailTitle'=>$equipSend->title,
            'MailContent'=>$equipSend->description,
            'SenderName'=>'系统',
            'RoleIdList'=>!empty($RoleIdList) ? $RoleIdList : null,
            'AttaItems'=>!empty($AttaItems) ? $AttaItems : null,
            'AttaMoney'=>null,
        ];

        try{
            $row = Server::query()->where('can_push',1)->where("server_id",$equipSend->game_area)->first();
            $pushUrl = data_get($row,'push_url');
            Log::info("/Api/Mail/Add: \n " . json_encode($requestBody));
            $response = Http::withHeaders(['Content-Type'=>'application/json'])
                ->timeout(5)
                ->post($pushUrl.'/Api/Mail/Add',$requestBody);
            $body = json_decode($response->body(),true);
            $RetCode = data_get($body,'RetCode');

            if ($RetCode == 1000) {
                throw new \Exception('参数错误');
            } else if($RetCode==2000){
                //throw new \Exception('操作正在处理');
                $equipSend->send_status = 1;
                $equipSend->save();
                return true;
            } else if ($RetCode == 0 ) {
                $equipSend->send_status = 1;
                $equipSend->send_status = 1;
                $equipSend->save();
                return true;
            }

        } catch (\Exception $e) {

            throw $e;
        }
    }
}
